package mobileann.mafamily.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.entity.GoodsListEntity;
import mobileann.mafamily.entity.MallGoodsEntity;
import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.mofind.android.net.HttpUtils;
import com.mofind.android.net.HttpUtils.HttpResultCallback;
import com.mofind.android.net.JSONParser;

public class CoinMallUtils {
    private static CoinMallUtils instance = null;
    public static final int GOODLIST_SUCCESS=601;
    public static final int GOODLIST_ERROR=602;
    public static final int GOODLIST_NULL=603;
    public static final int EXCHANGE_SUCCESS=604;
    public static final int EXCHANGE_FAIL=605;
    public static final int EXCHANGED_SUCCESS=606;
    public static final int EXCHANGED_ERROR=607;
    public static final int EXCHANGED_NULL=608;
    public static final int GETCHANGEDID_SUCCESS=609;
    public static final int GETCHANGEDID_ERROR=610;
    public static final int GETCHANGEDID_NULL=611;
    
    public static CoinMallUtils getInstance() {
	if (instance == null) {
	    instance = new CoinMallUtils();
	}
	return instance;
    }
    public void getGoodsList(final int page,final Handler handler){
	HttpUtils.startHttpGet(URLUtils.URL_TASK_GET+page+"_all"+"_IntegralMallGoodsList", new HttpResultCallback() {
	    
	    @Override
	    public void result(String url, boolean isResult, String jsonStr) {
		// TODO Auto-generated method stub
		if(isResult){
		    String json1=TripleDESUtil.CBCDecode(page+"","all", jsonStr);
		    if(TextUtils.isEmpty(json1)){
			if(handler!=null){
			    handler.obtainMessage(GOODLIST_ERROR).sendToTarget();
			}
		    }else{
			int end=json1.lastIndexOf("}");
			String json=json1.substring(0, end+1);
			JSONObject jo=JSONParser.getJSONObject(json);
			String status=JSONParser.getString(jo, "status");
			if(!TextUtils.isEmpty(status)){
			    if(handler!=null){
				handler.obtainMessage(GOODLIST_ERROR).sendToTarget();
			    }
			}else{
			    int totalPage=JSONParser.getInt(jo, "total_page");
			    if(totalPage==0){
				if(handler!=null){
				    handler.obtainMessage(GOODLIST_NULL).sendToTarget();
				}
			    }else{
				int page=JSONParser.getInt(jo, "page");
				int goods_amount=JSONParser.getInt(jo, "goods_amount");
				String goods1=JSONParser.getString(jo, "goods");
				JSONArray ja=JSONParser.getJSONArray(goods1);
				List<GoodsListEntity> goodsList=new ArrayList<GoodsListEntity>();
				for(int i=0;i<ja.length();i++){
				    JSONObject object = JSONParser.getJSONObject(ja, i);
				    int id=JSONParser.getInt(object, "gid");
				    String name=JSONParser.getString(object, "name");
				    int type=JSONParser.getInt(object, "type");
				    int amount=JSONParser.getInt(object, "amount");
				    int sale_amount=JSONParser.getInt(object, "sale_amount");
				    int price=JSONParser.getInt(object, "price");
				    int limit_quantity=JSONParser.getInt(object, "limit_quantity");
				    int limit_level=JSONParser.getInt(object, "limit_level");
				    String image=JSONParser.getString(object, "image");
				    String instru=JSONParser.getString(object,"instruction");
				    int isEntity=JSONParser.getInt(object, "is_entity");
				    GoodsListEntity goods=new GoodsListEntity(id, name, type, amount, sale_amount, price, limit_quantity, limit_level, image, instru,isEntity);
				    goodsList.add(goods);
				}
				MallGoodsEntity entity=new MallGoodsEntity(totalPage, page, goods_amount, goodsList);
				if(handler!=null){
				    handler.obtainMessage(GOODLIST_SUCCESS,entity).sendToTarget();
				}
			    }
			}
		    }
		}else{
		    if(handler!=null){
			handler.obtainMessage(GOODLIST_ERROR).sendToTarget();
			}
		}
	    }
	});
    }
    public String getGoodsImgPath(Context c) {
	String path = c.getFilesDir().getAbsolutePath() + File.separator
			+ "MABaby" + "/MAFamilyGoodsImage";
	String state = Environment.getExternalStorageState();
	if (Environment.MEDIA_MOUNTED.equals(state)) {
		path = (Environment.getExternalStorageDirectory() + File.separator
				+ "MABaby" + "/MAFamilyGoodsImage");
	}
	File dir = new File(path);
	if (!dir.exists()) {
		dir.mkdir();
	}
	dir = null;
	return path;
    }
    public Bitmap getSDBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
   }
    public Bitmap loadImage(String url) {  
        Bitmap bitmap = null;  
        HttpClient client = new DefaultHttpClient();  
        HttpResponse response = null;  
        InputStream inputStream = null;  
        try {  
            response = client.execute(new HttpGet(url));  
            HttpEntity entity = response.getEntity();  
            inputStream = entity.getContent(); 
            bitmap = BitmapFactory.decodeStream(inputStream);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return bitmap;  
    }  
    public void saveImgToSD( String photoName,Bitmap bitmap) {
            File photoFile = new File(getGoodsImgPath(FS.getInstance()), photoName); //在指定路径下创建文件
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (bitmap != null) {
                    if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                            fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                	if(fileOutputStream!=null)
                		fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
    public String getImgName(String url){
	String urlStr="";
	if(!TextUtils.isEmpty(url)){
	    String[] urls=url.split("\\/");
	    if(urls.length!=0){
		urlStr=urls[urls.length-1];
	    }
	}
        return urlStr;
    }
    private static Map<String, String> getExchangePara(String goodsId,int isEntity,String phone,String address,String linkman) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("from", "integral_buy_goods");
	map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
	map.put("data",
		TripleDESUtil.CBCEncode(SPUtils.getMySelf(SPUtils.MYUID), SPUtils.getMySelf(SPUtils.MYIRAD),
			getExchangeJson(goodsId, isEntity,phone,address,linkman)));
	return map;
    }

    private static String getExchangeJson(String goodsId,int isEntity,String phone,String address,String linkman) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("uid",SPUtils.getMySelf(SPUtils.MYUID));
	map.put("goods_id",goodsId );
	if(isEntity==1){
	    map.put("phone", phone);
	    map.put("address", address);
	    map.put("linkman", linkman);
	}
	String data = MyTaskUtils.getInstance().map2json(map);
	return data;
    }
    public void doExchangeGoods(String goodsId,int isEntity,String phone,String address,String linkman,final Handler handler){
	HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getExchangePara(goodsId, isEntity, phone, address, linkman), new HttpResultCallback() {
	    
	    @Override
	    public void result(String url, boolean isResult, String jsonStr) {
		// TODO Auto-generated method stub
		if(isResult){
		    if(!TextUtils.isEmpty(jsonStr)){
			String json = TripleDESUtil.getJsonObjStr(SPUtils.getMySelf(SPUtils.MYUID),
				SPUtils.getMySelf(SPUtils.MYIRAD), jsonStr);
			JSONObject jo = JSONParser.getJSONObject(json);
			String status=JSONParser.getString(jo, "status");
			String msg=JSONParser.getString(jo, "msg");
			if(handler!=null){
			    if("true".equals(status)){
				handler.obtainMessage(EXCHANGE_SUCCESS,msg).sendToTarget();
			    }else if("false".equals(status)){
				handler.obtainMessage(EXCHANGE_FAIL,msg).sendToTarget();
			    }
			}
		    }
		}
	    }
	});
    }
    public void getExchangedGoods(final int page,final Handler handler){
	HttpUtils.startHttpGet(URLUtils.URL_TASK_GET+SPUtils.getMySelf(SPUtils.MYUID)+"_"+SPUtils.getMySelf(SPUtils.MYIRAD)+"_"+page+"_IntegralMallGoodsUser", new HttpResultCallback() {
	    
	    @Override
	    public void result(String url, boolean isResult, String jsonStr) {
		// TODO Auto-generated method stub
		if(isResult){
		    String json=TripleDESUtil.CBCDecode(SPUtils.getMySelf(SPUtils.MYUID),SPUtils.getMySelf(SPUtils.MYIRAD), jsonStr);
		    if(TextUtils.isEmpty(json)){
			if(handler!=null){
			    handler.obtainMessage(EXCHANGED_ERROR).sendToTarget();
			}
		    }else{
			JSONObject jo=JSONParser.getJSONObject(json);
			String status=JSONParser.getString(jo, "status");
			if(!TextUtils.isEmpty(status)){
			    if(handler!=null){
				handler.obtainMessage(EXCHANGED_ERROR).sendToTarget();
			    }
			}else{
			    int totalPage=JSONParser.getInt(jo, "total_page");
			    if(totalPage==0){
				if(handler!=null){
				    handler.obtainMessage(EXCHANGED_NULL).sendToTarget();
				}
			    }else{
				int page=JSONParser.getInt(jo, "page");
				int goods_amount=JSONParser.getInt(jo, "goods_amount");
				String goods1=JSONParser.getString(jo, "goods");
				JSONArray ja=JSONParser.getJSONArray(goods1);
				List<GoodsListEntity> goodsList=new ArrayList<GoodsListEntity>();
				for(int i=0;i<ja.length();i++){
				    JSONObject object = JSONParser.getJSONObject(ja, i);
				    String name=JSONParser.getString(object, "name");
				    int price=JSONParser.getInt(object, "price");
				    String image=JSONParser.getString(object, "image");
				    String sn=JSONParser.getString(object,"sn");
				    String courier_name=JSONParser.getString(object, "courier_name");
				    String courier_number=JSONParser.getString(object,"courier_number");
				    String date=JSONParser.getString(object, "date");
				    String instru=JSONParser.getString(object,"instruction");
				    String detail=JSONParser.getString(object, "detail");
				    GoodsListEntity goods=new GoodsListEntity(name, price, image, instru, sn, courier_name, courier_number, date,detail);
				    goodsList.add(goods);
				}
				MallGoodsEntity entity=new MallGoodsEntity(totalPage, page, goods_amount, goodsList);
				if(handler!=null){
				    handler.obtainMessage(EXCHANGED_SUCCESS,entity).sendToTarget();
				}
			    }
			}
		    }
		}else{
		    if(handler!=null){
			handler.obtainMessage(GOODLIST_ERROR).sendToTarget();
			}
		}
	    }
	});
    }
    public void getChangedId(final Handler handler){
	HttpUtils.startHttpGet(URLUtils.URL_TASK_GET+SPUtils.getMySelf(SPUtils.MYUID)+"_"+SPUtils.getMySelf(SPUtils.MYIRAD)+"_IntegralMallGoodsIdUser", new HttpResultCallback() {
	    
	    @Override
	    public void result(String url, boolean isResult, String jsonStr) {
		// TODO Auto-generated method stub
		if(isResult){
		    String json=TripleDESUtil.CBCDecode(SPUtils.getMySelf(SPUtils.MYUID),SPUtils.getMySelf(SPUtils.MYIRAD), jsonStr);
		    if(TextUtils.isEmpty(json)){
			if(handler!=null){
			    handler.obtainMessage(GETCHANGEDID_ERROR).sendToTarget();
			}
		    }else{
			if(json.startsWith("{")){
			    if(handler!=null){
				    handler.obtainMessage(GETCHANGEDID_ERROR).sendToTarget();
			    }
			}else if(json.startsWith("[")){
			    int end=json.lastIndexOf("]");
			    String data=json.substring(1,end);
			    String[] ids=data.split(",");
			    if(ids.length==0){
				if(handler!=null){
				    handler.obtainMessage(GETCHANGEDID_ERROR).sendToTarget();
				}
			    }else{
				if(handler!=null){
				    handler.obtainMessage(GETCHANGEDID_SUCCESS,ids).sendToTarget();
				}
			    }
			}
		    }
		}
	    }
	});
    }
}
